package com.chiaching.pms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chiaching.common.utils.PageUtils;
import com.chiaching.common.utils.Query;
import com.chiaching.pms.dao.PmsCategoryDao;
import com.chiaching.pms.entity.PmsCategoryEntity;
import com.chiaching.pms.service.PmsCategoryService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, PmsCategoryEntity> implements PmsCategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsCategoryEntity> page = this.page(
                new Query<PmsCategoryEntity>().getPage(params),
                new QueryWrapper<PmsCategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<PmsCategoryEntity> queryList(PmsCategoryEntity pmsCategoryEntity) {
        return listByMap(BeanUtil.beanToMap(pmsCategoryEntity,true,true));
    }

    @Override
    public List<PmsCategoryEntity> queryTree() {
        List<PmsCategoryEntity> pmsCategoryEntities = list();
        List<PmsCategoryEntity> rootList = pmsCategoryEntities.stream().filter(e -> 0 == e.getParentCid()).collect(Collectors.toList());
        return rootList.stream().peek(e -> setChildCategory(e, pmsCategoryEntities)).sorted(Comparator.comparingInt(e -> (Objects.nonNull(e.getSort()) ? e.getSort() : 0)))
                .collect(Collectors.toList());
    }


    public void setChildCategory(PmsCategoryEntity root,List<PmsCategoryEntity> all){
        List<PmsCategoryEntity> childs = all.stream().filter(e -> e.getParentCid().equals(root.getCatId()))
                .sorted(Comparator.comparingInt(e -> (Objects.nonNull(e.getSort()) ? e.getSort() : 0)))
                .collect(Collectors.toList());
        root.setChilds(childs);
        if (CollUtil.isNotEmpty(childs)){
            childs.stream().peek(e -> setChildCategory(e, all));
        }
    }


}